
package GUIs;

import controllers.PublicationController;
import java.awt.HeadlessException;
import java.text.ParseException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;


public class them extends javax.swing.JFrame {

    private static them _instance; //Kiểm tra sự tồn tại của 2 instance trong cùng 1 form
    private PublicationController pubs;

    public them() {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    public them(PublicationController pubs) {
        initComponents();
        this.pubs = pubs;
    }

    public static them getInstance(PublicationController pubs) {
        if (_instance == null) {
            _instance = new them(pubs);
        }
        return _instance;
    }

    public void createAndShowUI() {
        setVisible(true);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnchinh = new javax.swing.JPanel();
        lbtensach = new javax.swing.JLabel();
        tftensach = new javax.swing.JTextField();
        lbnamxb = new javax.swing.JLabel();
        tfnamxb = new javax.swing.JTextField();
        btnthemsach = new javax.swing.JButton();
        btnthemtg = new javax.swing.JButton();
        thoat = new javax.swing.JButton();
        tftentg = new javax.swing.JTextField();
        lbtentg = new javax.swing.JLabel();
        lbngaysinh = new javax.swing.JLabel();
        sptacgia = new javax.swing.JScrollPane();
        tabletacgia = new javax.swing.JTable();
        btnxoatg = new javax.swing.JButton();
        btnsuatacgia = new javax.swing.JButton();
        tfngaysinh = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowDeactivated(java.awt.event.WindowEvent evt) {
                formWindowDeactivated(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        lbtensach.setText("Tên sách");

        lbnamxb.setText("Năm xuất bản");

        btnthemsach.setText("Thêm sách");
        btnthemsach.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnthemsachActionPerformed(evt);
            }
        });

        btnthemtg.setText("Thêm tác giả");
        btnthemtg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnthemtgActionPerformed(evt);
            }
        });

        thoat.setText("Thoát");
        thoat.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                thoatActionPerformed(evt);
            }
        });

        lbtentg.setText("Tên tác giả");

        lbngaysinh.setText("Ngày sinh");

        tabletacgia.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "STT", "Tên tác giả", "Ngày sinh"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Byte.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tabletacgia.getTableHeader().setReorderingAllowed(false);
        sptacgia.setViewportView(tabletacgia);
        if (tabletacgia.getColumnModel().getColumnCount() > 0) {
            tabletacgia.getColumnModel().getColumn(0).setResizable(false);
            tabletacgia.getColumnModel().getColumn(1).setResizable(false);
            tabletacgia.getColumnModel().getColumn(2).setResizable(false);
        }

        btnxoatg.setText("Xóa tác giả");
        btnxoatg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnxoatgActionPerformed(evt);
            }
        });

        btnsuatacgia.setText("Sửa tác giả");
        btnsuatacgia.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnsuatacgiaActionPerformed(evt);
            }
        });

        tfngaysinh.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("dd/M/yyyy"))));

        javax.swing.GroupLayout pnchinhLayout = new javax.swing.GroupLayout(pnchinh);
        pnchinh.setLayout(pnchinhLayout);
        pnchinhLayout.setHorizontalGroup(
            pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnchinhLayout.createSequentialGroup()
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnchinhLayout.createSequentialGroup()
                        .addGap(24, 24, 24)
                        .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnchinhLayout.createSequentialGroup()
                                .addComponent(lbtensach)
                                .addGap(18, 18, 18)
                                .addComponent(tftensach))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnchinhLayout.createSequentialGroup()
                                .addComponent(lbnamxb)
                                .addGap(18, 18, 18)
                                .addComponent(tfnamxb))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnchinhLayout.createSequentialGroup()
                                .addComponent(lbtentg)
                                .addGap(18, 18, 18)
                                .addComponent(tftentg))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnchinhLayout.createSequentialGroup()
                                .addComponent(lbngaysinh)
                                .addGap(18, 18, 18)
                                .addComponent(tfngaysinh))))
                    .addGroup(pnchinhLayout.createSequentialGroup()
                        .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnthemsach, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnsuatacgia, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(btnthemtg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(btnxoatg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(thoat))
                    .addComponent(sptacgia, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnchinhLayout.setVerticalGroup(
            pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnchinhLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnchinhLayout.createSequentialGroup()
                        .addGap(6, 6, 6)
                        .addComponent(lbtensach, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addComponent(tftensach, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbnamxb, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tfnamxb))
                .addGap(18, 18, 18)
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lbtentg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(tftentg))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnchinhLayout.createSequentialGroup()
                        .addComponent(lbngaysinh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(13, 13, 13))
                    .addComponent(tfngaysinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addComponent(sptacgia, javax.swing.GroupLayout.PREFERRED_SIZE, 150, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnthemsach, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(btnthemtg, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(thoat, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnchinhLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnxoatg)
                    .addComponent(btnsuatacgia))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnchinh, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnchinh, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnthemsachActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnthemsachActionPerformed
        String txttensach = tftensach.getText().trim();
        String txtnamxb = tfnamxb.getText().trim();
        if (txttensach.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Bạn chưa nhập tên sách!");
            tftensach.requestFocus();
        } else if (txtnamxb.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Bạn chưa nhập năm xuất bản!");
            tfnamxb.requestFocus();
        } else {
            int nRow = tabletacgia.getRowCount(), nCol = tabletacgia.getColumnCount();
            if (nRow >= 1) {
                Object[][] tableData = new Object[nRow][nCol];
                for (int i = 0; i < nRow; i++) {
                    for (int j = 0; j < nCol; j++) {
                        tableData[i][j] = tabletacgia.getValueAt(i, j);
                    }
                }
                try {
                    int nam = Integer.parseInt(txtnamxb);
                    this.pubs.add(txttensach, nam, tableData);
                    int dialogResult = JOptionPane.showConfirmDialog(this, "Thêm sách thành công! \nBạn có muốn tiếp tục thêm?\nNhấn yes để tiếp tục, no để thoát khung.", "Warning", JOptionPane.YES_NO_OPTION);
                    this.clearform();
                    if (dialogResult == JOptionPane.NO_OPTION) {
                        this.dispose();
                    }
                } catch (NumberFormatException | ParseException | HeadlessException ex) {
                    JOptionPane.showMessageDialog(this, "Năm xuất bản không hợp lệ");
                    tfnamxb.requestFocus();
                }
            } else {
                JOptionPane.showMessageDialog(this, "Vui lòng thêm ít nhất 1 tác giả");
                tftentg.requestFocus();
            }
        }
    }//GEN-LAST:event_btnthemsachActionPerformed

    private void clearform() {
        tftensach.requestFocus();
        tftensach.setText(null);
        tfnamxb.setText(null);
        tftentg.setText(null);
        tfngaysinh.setText(null);
        tabletacgia.setModel(new DefaultTableModel(
                new Object[][]{},
                new String[]{
                    "STT", "Tên tác giả", "Ngày sinh"
                }
        ) {
            Class[] types = new Class[]{
                java.lang.Byte.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean[]{
                false, false, false
            };

            @Override
            public Class getColumnClass(int columnIndex) {
                return types[columnIndex];
            }

            @Override
            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
    }

    private void btnthemtgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnthemtgActionPerformed
        String txttentg = tftentg.getText().trim();
        String txtngaysinh = tfngaysinh.getText().trim();
        if (txttentg.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Bạn chưa nhập tên tác giả!");
            tftentg.requestFocus();
        } else if (txtngaysinh.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Bạn chưa nhập ngày sinh!");
            tfngaysinh.requestFocus();
        } else {
            int stt = tabletacgia.getRowCount();
            for (int i = 0; i < stt; i++) {
                if (tabletacgia.getValueAt(i, 1).equals(txttentg)) {
                    tabletacgia.setValueAt(txttentg, i, 1);
                    tabletacgia.setValueAt(txtngaysinh, i, 2);
                    tftentg.requestFocus();
                    tftentg.setText(null);
                    tfngaysinh.setText(null);
                    return;
                }
            }
            DefaultTableModel model = (DefaultTableModel) tabletacgia.getModel();
            Object[] row = {++stt, txttentg, txtngaysinh};
            model.addRow(row);
            tftentg.requestFocus();
            tftentg.setText(null);
            tfngaysinh.setText(null);
        }
    }//GEN-LAST:event_btnthemtgActionPerformed

    private void thoatActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_thoatActionPerformed
        this.clearform();
        this.dispose();
    }//GEN-LAST:event_thoatActionPerformed

    private void formWindowDeactivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowDeactivated
        main change = main.getInstance(this.pubs.getConn());
    }//GEN-LAST:event_formWindowDeactivated

    private void btnxoatgActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnxoatgActionPerformed
        int numRow = tabletacgia.getSelectedRow();
        if (numRow != -1) {
            try {
                DefaultTableModel model = (DefaultTableModel) tabletacgia.getModel();
                model.removeRow(numRow);
                model.fireTableDataChanged();
                tftentg.setText(null);
                tfngaysinh.setText(null);
            } catch (Exception ex) {

            }
        } else {
            JOptionPane.showMessageDialog(this, "Chưa chọn tác giả nào!");
        }
    }//GEN-LAST:event_btnxoatgActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        tabletacgia.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                int row = tabletacgia.rowAtPoint(evt.getPoint());
                if (row >= 0) {
                    tftentg.setText(tabletacgia.getValueAt(row, 1).toString());
                    tfngaysinh.setText(tabletacgia.getValueAt(row, 2).toString());
                }
            }
        });
    }//GEN-LAST:event_formWindowOpened

    private void btnsuatacgiaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnsuatacgiaActionPerformed
        int numRow = tabletacgia.getSelectedRow();
        if (numRow != -1) {
            String txttentg = tftentg.getText().trim();
            String txtngaysinh = tfngaysinh.getText().trim();
            if (txttentg.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Bạn chưa nhập tên tác giả!");
                tftentg.requestFocus();
            } else if (txtngaysinh.isEmpty()) {
                JOptionPane.showMessageDialog(this, "Bạn chưa nhập ngày sinh!");
                tfngaysinh.requestFocus();
            } else {
                tabletacgia.setValueAt(txttentg, numRow, 1);
                tabletacgia.setValueAt(txtngaysinh, numRow, 2);
            }
        } else {
            btnthemtgActionPerformed(null);
        }
    }//GEN-LAST:event_btnsuatacgiaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(them.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(them.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(them.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(them.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new them().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnsuatacgia;
    private javax.swing.JButton btnthemsach;
    private javax.swing.JButton btnthemtg;
    private javax.swing.JButton btnxoatg;
    private javax.swing.JLabel lbnamxb;
    private javax.swing.JLabel lbngaysinh;
    private javax.swing.JLabel lbtensach;
    private javax.swing.JLabel lbtentg;
    private javax.swing.JPanel pnchinh;
    private javax.swing.JScrollPane sptacgia;
    private javax.swing.JTable tabletacgia;
    private javax.swing.JTextField tfnamxb;
    private javax.swing.JFormattedTextField tfngaysinh;
    private javax.swing.JTextField tftensach;
    private javax.swing.JTextField tftentg;
    private javax.swing.JButton thoat;
    // End of variables declaration//GEN-END:variables
}
